<template>
    <div class="centerWarp" v-loading="allCheckLoading">
      <div>
        <el-card class="box-card">
          <div class="nameStyle" :style="{ height: heightCard }">
            <p
              v-for="(item, index) in personList"
              :key="index"
              @click="handlePersonListClick(item, index)"
              :class="{ highlight: item === curPersonRow }"
            >
              {{ item.personName }}
            </p>
          </div>
        </el-card>
      </div>
      <div>
        <el-card class="box-card">
          <div :style="{ height: heightCard }" class="selectimgs-warp">
            <h2>授权表：</h2>
            <p>{{ getEmpowerTextNotJpg }}</p>
          </div>
        </el-card>
      </div>
      <div class="left" :style="{ height: heightTree }">
        <el-tree
          ref="tree"
          class="dc-tree-c"
          :data="personTreeList"
          node-key="id"
          :props="defaultProps"
          highlight-current
          @node-click="handleTreeNodeClick"
          :current-node-key="currentNodekey"
          :default-expanded-keys="[currentNodekey]"
        ></el-tree>
      </div>
      <div class="right">
        <div class="thumbnail" :style="{ height: heightY }">
          <el-checkbox
            style="margin-left: 7px"
            :indeterminate="isAllIndeterminate"
            v-model="isAllCheckbox"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <!-- 图片和选择框 -->
          <el-checkbox-group :value="imagesCheckVals">
            <div
              class="image-container"
              v-for="(item, index) in imagesSelectList"
              :key="index"
            >
              <el-checkbox
                :key="item.elecId"
                :label="getDictName + '_' + item.fileName"
                @change="handleCheckboxChange($event, getDictName + '_' + item.fileName)"
              ></el-checkbox>
              <img
                class="cd-checkiam"
                :class="{ 'check-active': index === selectedImageIndex }"
                :src="item.tImg"
                @click="hanldeSelectImage(index)"
              />
            </div>
          </el-checkbox-group>
        </div>
        <div class="bigPicture" :style="{ height: heightY }">
          <img
            :src="
              selectedImageIndex !== null && imagesSelectList[selectedImageIndex]
                ? imagesSelectList[selectedImageIndex].tImg
                : ''
            "
            alt=""
            style="width: 100%; height: 100%"
          />
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import {
    getMaterialTree,
    clickMaterial,
    getImgFromCacheByFlag,
  } from "@/api/datacentersg/achives/documentApi";
  
  import { treeToList } from '@/utils/index.js'
  
  export default {
    name: "DocumentCenter",
    props: {
      personList: {
        type: Array,
        default: () => [],
      },
    },
    watch: {
      personList: {
        deep: true,
        handler(val) {
          const [item] = val;
          this.imagesCheckVals = []
          this.tempImagesCheckVals = []
          this.handlePersonList(item, 0);
        },
      },
      imagesCheckVals(val) {
        this.$nextTick(this.onGetAllIndeterminateStatus)
      }
    },
    computed: {
      getDictName() {
        const { name } = this.currentTreeItem || {}
        return name || ''
      },
      getEmpowerText() { // 给后端保存的时候可以 使用这个
        if(this.isAllCheckbox) return '全部';
        let selectImages = this.imagesCheckVals
        return selectImages.join(',')
      },
      getEmpowerTextNotJpg() {
        if(this.isAllCheckbox) return '全部'; // 这个就是 展示 全部 文字，不需要了直接注解就行
        let selectImages = this.imagesCheckVals
        let txt = selectImages.join(',')
        return txt.replace(new RegExp('.jpg', 'g'), '')
      }
    },
    data() {
      return {
        heightCard: window.innerHeight - 320 + "px",
        heightY: window.innerHeight - 280 + "px",
        heightTree: window.innerHeight - 280 + "px",
        defaultProps: {
          children: "children",
          label: "name",
        },
        personTreeList: [],
        currentNodekey: "",
        currentTreeItem: null,
        curPersonRow: null, // 选择人员的
        isAllIndeterminate: false, // 半选状态 这两个可以忽略
        isAllCheckbox: false, // 是不是全选 这两个可以忽略
        imagesSelectList: [], // 当前的图片列表，是根据每个 子集获取的
        imagesCheckVals: [], // 选中的图片
        selectedImageIndex: 0, // 当前图片
        tempImagesCheckVals: [], // 暂存 选中的数据
        personParentImageTreeList: [], // 所有的子集集合
        allCheckLoading: false,
        tcurrentSelectImage: [],
        name: "",
        idCard: "",
      };
    },
    mounted() {
      this.imagesCheckVals = []
      this.tempImagesCheckVals = []
      const [item] = this.personList;
    },
    methods: {
      handlePersonList(item, ix) {
        if(item) {
          this.curPersonRow = item;
          this.name = item.personName
          this.idCard = item.idCard
          console.log(this.name,this.idCard,"123")
          this.getMaterialTree();
        }
      },
      handlePersonListClick(item) {
        this.isAllCheckbox = false;
        this.imagesCheckVals = []
        this.tempImagesCheckVals = []
        this.handlePersonList(item,0);
      },
      // tree树的数据
      getMaterialTree() {
        const params = {
          name:this.name,
          idCard:this.idCard,
        };
        getMaterialTree(params).then((res) => {
          const { res_code, res_data, res_msg } = res.data;
          if (res_code === "0000") {
            this.personTreeList = res_data;
            this.personParentImageTreeList = this.getNotChildrens(treeToList(res_data))
            
            // 只要详情那边是 全部的时候，就直接 请求全部的数据
            this.getAllSelectImageData(this.personParentImageTreeList)
            this.handleTreeNodeClick(this.getMateItem(this.personTreeList));
          } else if (res_code === "0001") {
            this.personTreeList = [];
            this.imagesSelectList = [];
            this.$message({
              message: res_msg,
              type: "warning",
            });
          }
        });
      },
      handleTreeNodeClick(e) {
        if (Array.isArray(e.children)) return;
        this.currentTreeItem = e;
        this.currentNodekey = e.id;
        console.log(this.currentNodekey,"currentNodekey")
        // console.log('treeid', e.id)
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(e.id)
        })
        this.getSelectImages(this.currentNodekey).then(res => {
          this.imagesSelectList = res;
          this.getImagesSelectList()
        });
        
      },
  
      getSelectImages(maid) {
        // console.log(maid,"maid")
        return new Promise((resolve, reject) => {
          const params = {
            name:this.name,
            idCard:this.idCard,
            materialid: maid, //点击的目录ID
          };
          clickMaterial(params).then((res) => {
            const {code,data: { res_data },} = res;
            if (code === 0) {
              resolve(res_data);
              return
            }
            reject()
          }).catch(reject);
        })
      },
  
      getImagesSelectList() {
        this.imagesSelectList.forEach((item, i) => {
          const paramsNew = {
            name:this.name,
            idCard:this.idCard,
            fileName: item.fileName, //文件名
          };
          getImgFromCacheByFlag(paramsNew).then((result) => {
            if (result.code === 0) {
              this.$set(item, "tImg", result.data.res_data);
            }
          });
        });
      },
  
      onGetAllIndeterminateStatus() {
        let len = this.imagesCheckVals.length
        this.isAllIndeterminate = len > 0 && len < this.tempImagesCheckVals.length
        if(!(this.tempImagesCheckVals.length === 0 && len === 0)) {
          this.isAllCheckbox = len === this.tempImagesCheckVals.length
        }
      },
  
      // 全选
      handleCheckAllChange(check) {
        if (!this.curPersonRow) {
          this.$message({
            message: "请先选择授权人员",
            type: "warning",
          });
          return
        }
        if (!this.currentTreeItem) {
          this.$message({
            message: "请选择相应目录树",
            type: "warning",
          });
          return
        }
        // 选中了 全部的时候，直接让请求
        if(check) {
          this.isAllIndeterminate = false
          this.$nextTick(() => {
            this.getAllSelectImageData(this.personParentImageTreeList)
          })
        } else {
          // 不是选中的时候，直接让全部清空
          // this.tempImagesCheckVals = []
          this.imagesCheckVals = []
        }
      },
      //单选
      handleCheckboxChange(check, val) {
        if (!this.curPersonRow) {
          this.$message({
            message: "请先选择授权人员",
            type: "warning",
          });
          return
        }
        if (!this.currentTreeItem) {
          this.$message({
            message: "请选择相应目录树",
            type: "warning",
          });
          return
        }
  
        if(check) {
          this.imagesCheckVals.push(val)
        } else {
          let index = this.imagesCheckVals.indexOf(val)
          if(index > -1) {
            this.imagesCheckVals.splice(index, 1)
          }
        }
        // console.log('check', this.imagesCheckVals)
      },
      handleCheckedCitiesChange() {
        this.$nextTick(() => {
          // console.log('check', this.imagesCheckVals)
        })
      },
      // 点击小图切换大图
      hanldeSelectImage(index) {
        this.selectedImageIndex = index;
      },
  
      setAllChecked(check = false) {
        if(check) {
          this.isAllIndeterminate = false
          this.isAllCheckbox = true
        } else {
          this.isAllIndeterminate = false
          this.isAllCheckbox = false
        }
      },
  
      // 设置要回显的数据
      setSelectIamge(text) {
        let list = text.split(",")
        this.tcurrentSelectImage = list
      },
  
      async getAllSelectImageData() {
        if(Array.isArray(this.tempImagesCheckVals) && this.tempImagesCheckVals.length > 0) {
          if(this.isAllCheckbox) {
            this.imagesCheckVals = [...this.tempImagesCheckVals]
          }
          return this.tempImagesCheckVals // 性能优化 假如全部请求过了，就不做请求了，因为是全部的数据，没有必要再次请求了
        }
        this.allCheckLoading = true
        try {
          this.tempImagesCheckVals = []
          let parentTreeList = this.personParentImageTreeList
          for (let i = 0; i < parentTreeList.length; i++) {
            const tree = parentTreeList[i];
            let list = await this.getSelectImages(tree.id)
            console.log(tree.id, "tree.id")
            list = list.map(e => tree.name + '_' + e.fileName)
            this.tempImagesCheckVals = [...this.tempImagesCheckVals, ...list]
          }
          // console.log('check', this.imagesCheckVals, this.tempImagesCheckVals)
          if(this.isAllCheckbox) {
            this.imagesCheckVals = [...this.tempImagesCheckVals]
          } else {
            this.imagesCheckVals = [...this.tcurrentSelectImage]
          }
          this.allCheckLoading = false
          return this.tempImagesCheckVals
        } catch (error) {
          // console.error('getAllSelectImage', error)
          this.allCheckLoading = false
        }
      },
  
      getEmpowerStr() {
        return {
          dataId: this.curPersonRow.dataId,
          text: this.getEmpowerText
        } 
      },
  
      getNotChildrens(list) {
        return list.filter(f => !Array.isArray(f.children))
      },
  
      getMateItem(list) {
        const [treeItem] = list;
        if (treeItem && Array.isArray(treeItem.children)) {
          return this.getMateItem(treeItem.children);
        } else {
          return treeItem;
        }
      },
    },
  };
  </script>
  
  <style scoped>
  >>> .el-tree-node__content {
    height: 60px;
  }
  .centerWarp {
    display: flex;
  }
  /deep/ .el-tree > .el-tree-node > .el-tree-node__content {
    font-weight: 900;
    background: #cfe5fc;
  }
  /deep/
    .el-tree
    > .el-tree-node
    > .el-tree-node__children
    > .el-tree-node
    > .el-tree-node__content
    > .el-tree-node__label {
    font-weight: 700;
  }
  /deep/.el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: #6baef1;
  }
  
  >>> .el-tree-node__content {
    /* background-color: #CFE5FC; */
    margin-top: 2px;
  }
  
  .highlight {
    background-color: #c6e2ff;
    padding: 5px;
    height: 40px;
  }
  
  .nameStyle {
    text-align: center;
    font-size: 18px;
    color: #409eff;
    overflow-y: scroll;
  }
  .nameStyle p {
    padding: 5px;
    height: 40px;
  }
  
  .selectimgs-warp {
    width: 240px;
    text-align: center;
    margin-left: 5px;
    overflow-y: scroll;
  }
  
  .dc-tree-c {
    margin-left: 10px;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  
  .left {
    float: left;
    margin-left: 5px;
    background: #f7f2ec;
    width: 18.417vw;
    overflow-y: scroll;
  }
  .right {
    float: left;
    margin-left: 15px;
    background: #f7f2ec;
  }
  .thumbnail {
    width: 205px;
    overflow-y: scroll;
    float: left;
    margin-bottom: 5px;
    background: #fff;
  }
  .image-container {
    display: flex;
    padding-right: 0.521vw;
    margin-top: 5px;
    justify-content: space-around;
  }
  /* 将el-checkbox中的label隐藏了 */
  .image-container /deep/.el-checkbox__label {
    display: none;
  }
  .bigPicture {
    float: left;
    width: 600px;
    margin-bottom: 5px;
    margin-right: 10px;
    background: #fff;
    margin-left: 10px;
  }
  
  .cd-checkiam {
    width: 140px;
    height: 200px;
  }
  
  .cd-checkiam.check-active {
    border: 2px solid red;
  }
  </style>